// 云函数入口文件
const cloud = require('wx-server-sdk');

cloud.init({
  env: 'boyi-5g77xpkp0aa0181c'
});

// 云函数入口函数
exports.main = async (event, context) => {

  // 获取微信上下文
  const wxContext = cloud.getWXContext();

  /** 检查是否正确获取用户的openId start */
  if(wxContext.OPENID == undefined) {
    var result = {};
    result.errCode = 1;
    result.errMsg = "未能正确返回openId";
    var data = {};
    result.data = data;
    return result;
  }
  /** 检查是否正确获取用户openId end */

  /** 检查传入的参数是否完整 start */
  if (event.household == undefined) {
    var result = {};
    result.errCode = 2;
    result.errMsg = "传入的参数不完整";
    var data = {};
    result.data = data;
    return result;
  }
  /** 检查传入的参数是否完整 end */

  // 实例化数据库
  const db = cloud.database();

  /** 在住户表查找household对应的数据 start */
  var household;
  await db.collection('householdInfo')
  .where({
    name: event.household.name,
    phone: event.household.phone,
    building: event.household.building,
    room: event.household.room
  })
  .get()
  .then(res => {
    console.log(res.data[0]);
    household = res.data[0];
    console.log(household);
  });
  console.log(household);
  /** 在住户表中查找household对应的数据 end */
  
  // 没有查找到household对应的数据
  if(household == undefined) {
    console.log(household);
    var result = {};
    result.errCode = 0;
    result.errMsg = "未输入正确的住户信息";
    var data = {};
    data.correct = false;
    result.data = data;
    return result;
  }

  /** 检查该住户信息是否已经被其他用户绑定过 start */
  var user;
  await db.collection('userInfo')
  .where({
    name: household.name,
    phone: household.phone,
    building: household.building,
    room: household.room
  })
  .get()
  .then(res => {
    console.log(res.data);
    user = res.data[0];
  })
  /** 检查该住户信息是否已经被其他用户绑定过 end */

  // 该住户信息被其他用户绑定过
  if(user != undefined) {
    var result = {};
    result.errCode = 0;
    result.errMsg = "该住户信息已经被其他用户绑定";
    var data = {};
    data.correct = true;
    data.enable = false;
    result.data = data;
    return result;
  }

  /** 绑定该住户信息 start */
  await db.collection('userInfo')
  .add({
    data: {
      openId: wxContext.OPENID,
      name: household.name,
      phone: household.phone,
      building: household.building,
      room: household.room
    }
  })
  .then(res => {
    console.log(res);
  })
  /** 绑定该住户信息 end */

  // 返回数据
  var result = {};
  result.errCode = 0;
  result.errMsg = "住户信息绑定成功";
  var data = {};
  data.correct = true;
  data.enable = true;
  result.data = data;
  return result;
}